﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Edit_F4ExportTroubles : Form
    {
        private DataSet ds;
        private DataViewManager dsView;

        private DataSet reason_ds;
        private DataViewManager reason_dsView;

        private DataSet mistake_ds;
        private DataViewManager mistake_dsView;

        public string id;

        public frm_Edit_F4ExportTroubles()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.ds = new DataSet("TimePlan");
            this.reason_ds = new DataSet("MistakeReason");
            this.mistake_ds = new DataSet("Mistake");
            getCustomerList();
            this.reportDate.EditValue = DateTime.Now.Date;            
            getOrderNoList();
            getCheckerList();
            getSupplierList();
            this.NGTime.Text = "1";
            getReasonList();
            getMistakeList();
        }

        /////////////////////////////////////////
        /// Load Data to Edit Form
        /////////////////////////////////////////
        public bool LoadData()
        {
            bool ret = true;
            if (string.IsNullOrEmpty(this.id))
            {
                ret = false;
            }
            else
            {
                try
                {
                    ComboboxItem item = new ComboboxItem();

                    myConnection.Open();
                    SqlCommand sql_cmd = myConnection.CreateCommand();
                    sql_cmd.CommandText = "SELECT * FROM [231_F4Troubles] WHERE ID=" + this.id;
                    SqlDataReader dataReader = sql_cmd.ExecuteReader();
                    if (dataReader.Read())
                    {
                        this.yearText.Text = dataReader["Year"].ToString().Trim();
                        for (int i = 0; i < this.customerID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.customerID.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["CustomerID"].ToString())
                            {
                                this.customerID.SelectedIndex = i;
                            }
                        }

                        if (dataReader["Date"] != DBNull.Value)
                        {
                            this.exportDate.EditValue = DateTime.Parse(dataReader["Date"].ToString());
                        }

                        if (dataReader["ReportDate"] != DBNull.Value)
                        {
                            this.reportDate.EditValue = DateTime.Parse(dataReader["ReportDate"].ToString());
                        }

                        this.customerReportNo.Text = dataReader["CheckNo"].ToString();
                        this.assReportNo.Text = dataReader["ReportNo"].ToString();
                        this.NGTime.Text = dataReader["NGTime"].ToString();
                        this.monthText.Text = dataReader["Month"].ToString();
                        this.orderNo.Text = dataReader["TimePlanNo"].ToString();
                        this.serialNo.Text = dataReader["SerialNo"].ToString();
                        if (dataReader["Kind"].ToString().Trim().ToUpper() == "NEW")
                        {
                            this.kindList.SelectedIndex = 0;
                        }

                        if (dataReader["Kind"].ToString().Trim().ToUpper() == "Old")
                        {
                            this.kindList.SelectedIndex = 1;
                        }

                        this.exportQuantity.Text = dataReader["ExportQuantity"].ToString();
                        this.troubleQty.Text = dataReader["NGQuantity"].ToString();
                        //this.troubleContent.Text = dataReader["F4TroubleContent"].ToString();
                        //this.NGCode.Text = dataReader["NGCode"].ToString();

                        if (this.NGCode.FindString(dataReader["NGCode"].ToString().Trim()) > 0)
                        {
                            this.NGCode.SelectedIndex = this.NGCode.FindString(dataReader["NGCode"].ToString().Trim());
                        }

                        for (int i = 0; i < this.CheckerID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.CheckerID.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["Checker"].ToString())
                            {
                                this.CheckerID.SelectedIndex = i;
                            }
                        }

                        for (int i = 0; i < this.MadeByID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.MadeByID.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["MadeBy"].ToString())
                            {
                                this.MadeByID.SelectedIndex = i;
                            }
                        }
                        this.NGType.Text = dataReader["TroubleKind"].ToString();
                        //this.troubleReason.Text = dataReader["Reason"].ToString();
                        //this.ReasonCode.Text = dataReader["ReasonCode"].ToString();

                        if (this.ReasonCode.FindString(dataReader["ReasonCode"].ToString().Trim()) > 0)
                        {
                            this.ReasonCode.SelectedIndex = this.ReasonCode.FindString(dataReader["ReasonCode"].ToString().Trim());
                        }

                        this.SolutionText.Text = dataReader["Solution"].ToString();
                        this.NGKind.Text = dataReader["NGType"].ToString();
                        for (int i = 0; i < this.supplierID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.supplierID.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["SupplierID"].ToString())
                            {
                                this.supplierID.SelectedIndex = i;
                            }
                        }
                        this.troubleType.Text = dataReader["NGKind"].ToString();
                        for (int i = 0; i < this.ResponseID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.ResponseID.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["ResponsePerson"].ToString())
                            {
                                this.ResponseID.SelectedIndex = i;
                            }
                        }
                        this.remarkText.Text = dataReader["Remark"].ToString();
                        this.evaluationText.Text = dataReader["AssNote"].ToString();
                    }
                    dataReader.Close();
                    sql_cmd.Dispose();
                    myConnection.Close();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    ret = false;
                }
            }
            return ret;
        }
        
        ////////////////////////////////////////////////
        /// Load Order No list to form
        ////////////////////////////////////////////////
        private void getOrderNoList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT t1.TimePlanNo, t1.CompID, ISNULL(t2.PartEnglishName, t1.CompID) AS PartName"
                    + " FROM [231_TimePlan] AS t1 LEFT JOIN"
                    + " [222_Part] AS t2 ON t1.CompID=t2.PartNo"
                    + " WHERE (t1.FinishedDate IS NOT NULL)"
                    + " ORDER BY t1.TimePlanNo";
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = cmd_sql;
                da1.TableMappings.Add("Table", "TimePlan");
                da1.Fill(ds);
                dsView = ds.DefaultViewManager;

                cmd_sql.Dispose();
                myConnection.Close();
                
                this.orderNo.DataSource = dsView;
                this.orderNo.DisplayMember = "TimePlan.TimePlanNo";
                this.orderNo.ValueMember = "TimePlan.TimePlanNo";
                this.orderNo.AutoCompleteSource = AutoCompleteSource.ListItems;

                this.partNo.DataBindings.Add("Text", dsView, "TimePlan.CompID");
                this.partName.DataBindings.Add("Text", dsView, "TimePlan.PartName"); 
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get OrderNo list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Reason Code list to form
        ////////////////////////////////////////////////
        private void getReasonList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ReasonCode, ReasonName FROM [231_MistakeReason] ORDER BY ReasonCode";
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = cmd_sql;
                da1.TableMappings.Add("Table", "MistakeReason");
                da1.Fill(reason_ds);
                reason_dsView = reason_ds.DefaultViewManager;

                cmd_sql.Dispose();
                myConnection.Close();

                this.ReasonCode.DataSource = reason_dsView;
                this.ReasonCode.DisplayMember = "MistakeReason.ReasonCode";
                this.ReasonCode.ValueMember = "MistakeReason.ReasonCode";
                this.ReasonCode.AutoCompleteSource = AutoCompleteSource.ListItems;

                this.troubleReason.DataBindings.Add("Text", reason_dsView, "MistakeReason.ReasonName");
                
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot Reason Code list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Mistake list to form
        ////////////////////////////////////////////////
        private void getMistakeList()
        {            
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT MistakeCode, MistakeName FROM [231_Mistake] ORDER BY MistakeCode";
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = cmd_sql;
                da1.TableMappings.Add("Table", "Mistake");
                da1.Fill(mistake_ds);
                mistake_dsView = mistake_ds.DefaultViewManager;

                cmd_sql.Dispose();
                myConnection.Close();

                this.NGCode.DataSource = mistake_dsView;
                this.NGCode.DisplayMember = "Mistake.MistakeCode";
                this.NGCode.ValueMember = "Mistake.MistakeCode";
                this.NGCode.AutoCompleteSource = AutoCompleteSource.ListItems;

                this.troubleContent.DataBindings.Add("Text", mistake_dsView, "Mistake.MistakeName");

            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Mistake list");
            } 
        }

        ////////////////////////////////////////////////
        /// Load Customer list to form
        ////////////////////////////////////////////////
        private void getCustomerList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID, CustomerName FROM [231_Customer]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CustomerName"].ToString();
                    item.Value = dataReader["CustomerID"].ToString();
                    this.customerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Customer list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Staff list to Checker combobox
        ////////////////////////////////////////////////
        private void getCheckerList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT StaffID, StaffName"
                    + " FROM [222_Staff] WHERE StopDate IS NULL ORDER BY StaffName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["StaffID"].ToString() + " | " + dataReader["StaffName"].ToString();
                    item.Value = dataReader["StaffID"].ToString();
                    this.CheckerID.Properties.Items.Add(item);
                    this.MadeByID.Properties.Items.Add(item);
                    this.ResponseID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Checker list");
            }

            ComboboxItem kind = new ComboboxItem();
            kind.Text = "New";
            kind.Value = "New";
            this.kindList.Properties.Items.Add(kind);

            ComboboxItem kind2 = new ComboboxItem();
            kind2.Text = "Old";
            kind2.Value = "Old";
            this.kindList.Properties.Items.Add(kind2);
        }

        ////////////////////////////////////////////////
        /// Load Supplier list to form
        ////////////////////////////////////////////////
        private void getSupplierList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT [SupplierID] FROM [231_Supplier] ORDER BY [SupplierID]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["SupplierID"].ToString();
                    item.Value = dataReader["SupplierID"].ToString();
                    this.supplierID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Supplier list");
            }
        }
 

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;
            DateTime exportdate = new DateTime(), reportdate = new DateTime();
            string year = null, month = null;
            string cusreportno = null, assreportno = null;
            int ngtime = 1;
            string order = null, serial = null;
            string kind = null;
            int export_quantity = 0;
            int ng_quantity = 0;
            string ng_name = null, ng_code = null;
            string checker = null, madeby = null, response = null;
            string ng_type = null;
            string reason = null, reasoncode = null;
            string solution = null;
            string ng_kind = null;
            string supplier = null;
            string trouble_type = null;
            string remark = null;
            string evaluation = null;
            string customerid = null;

            ComboboxItem item = new ComboboxItem();

            if (string.IsNullOrEmpty(this.yearText.Text.Trim()))
            {
                error = "Please enter Year";
            }
            else
            {
                year = this.yearText.Text.Trim();
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.customerID.SelectedIndex < 0)
                {
                    error = "Please select Customer";
                }
                else
                {
                    item = (ComboboxItem)this.customerID.SelectedItem;
                    customerid = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!DateTime.TryParse(this.exportDate.DateTime.Date.ToString(), out exportdate))
                {
                    error = "Please select Export Date";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!DateTime.TryParse(this.reportDate.DateTime.Date.ToString(), out reportdate))
                {
                    error = "Please select Report Date";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.customerReportNo.Text.Trim()))
                {
                    error = "Please enter Customer Report No.";
                }
                else
                {
                    cusreportno = this.customerReportNo.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.assReportNo.Text.Trim()))
                {
                    error = "Please enter Ass. Report No.";
                }
                else
                {
                    assreportno = this.assReportNo.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.NGTime.Text.Trim()))
                {
                    error = "Please enter 'Lần xảy ra lỗi'";
                }
                else
                {
                    if (!Int32.TryParse(this.NGTime.Text.Trim(), out ngtime))
                    {
                        error = "Invalid 'Lần xảy ra lỗi'";
                    }
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.monthText.Text.Trim()))
                {
                    error = "Please enter Month";
                }
                else
                {
                    month = this.monthText.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.orderNo.SelectedIndex < 0)
                {
                    error = "Please Select Order No.";
                }
                else
                {
                    //order = this.orderNo.SelectedItem.ToString();
                    order = this.orderNo.Text;
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!Int32.TryParse(this.exportQuantity.Text, out export_quantity))
                {
                    error = "Invalid Export Quantity";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!Int32.TryParse(this.troubleQty.Text, out ng_quantity))
                {
                    error = "Invalid NG Quantity";
                }
                //trouble_quantity = selectedSerial.Count;               
            }

            if (string.IsNullOrEmpty(error))
            {
                if (ng_quantity <= 0)
                {
                    error = "NG quantity must be greater than 0";
                }
                else
                {
                    if (ng_quantity > export_quantity)
                    {
                        error = "NG quantity cannot be greater than Export quantity";
                    }
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.kindList.SelectedIndex < 0)
                {
                    error = "Please Select Kind.";
                }
                else
                {
                    item = (ComboboxItem)this.kindList.SelectedItem;
                    kind = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.troubleContent.Text.Trim()))
                {
                    error = "Please enter Mistake Name.";
                }
                else
                {
                    ng_name = this.troubleContent.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.NGCode.Text.Trim()))
                {
                    error = "Please enter Mistake Code.";
                }
                else
                {
                    ng_code = this.NGCode.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.MadeByID.SelectedIndex < 0)
                {
                    error = "Please Select Made By.";
                }
                else
                {
                    item = (ComboboxItem)this.MadeByID.SelectedItem;
                    madeby = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.CheckerID.SelectedIndex < 0)
                {
                    error = "Please Select Checker.";
                }
                else
                {
                    item = (ComboboxItem)this.CheckerID.SelectedItem;
                    checker = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.NGType.Text.Trim()))
                {
                    error = "Please enter Mistake Type.";
                }
                else
                {
                    ng_type = this.NGType.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.troubleReason.Text.Trim()))
                {
                    error = "Please enter Reason.";
                }
                else
                {
                    reason = this.troubleReason.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.ReasonCode.Text.Trim()))
                {
                    error = "Please enter Reason Code.";
                }
                else
                {
                    reasoncode = this.ReasonCode.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                serial = this.serialNo.Text.Trim();
                solution = this.SolutionText.Text.Trim();
                ng_kind = this.NGKind.Text.Trim();
                if (this.supplierID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.supplierID.SelectedItem;
                    supplier = item.Value.ToString();
                }
                trouble_type = this.troubleType.Text.Trim();

                if (this.ResponseID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.ResponseID.SelectedItem;
                    response = item.Value.ToString();
                }

                remark = this.remarkText.Text.Trim();
                evaluation = this.evaluationText.Text;

                try
                {
                    myConnection.Open();
                    string sql = "UPDATE [231_F4Troubles] SET [Year]='" + year + "', [CustomerID]='" + customerid + "',"
                        + " [Date]=@exportdate, [ReportDate]=@reportdate, [CheckNo]='" + cusreportno + "',"
                        + " [ReportNo]='" + assreportno + "', [NGTime]=" + ngtime.ToString() + ", [Month]='" + month + "',"
                        + " TimePlanNo='" + order + "', SerialNo='" + serial + "', [Kind]='" + kind + "',"
                        + " [ExportQuantity]=" + export_quantity.ToString() + ", [NGQuantity]=" + ng_quantity.ToString() + ","
                        + " F4TroubleContent=N'" + ng_name + "', [NGCode]='" + ng_code + "', Checker=N'" + checker + "',"
                        + " [MadeBy]=N'" + madeby + "', [TroubleKind]=N'" + ng_kind + "', Reason=N'" + reason + "',"
                        + " [ReasonCode]=N'" + reasoncode + "', Solution=N'" + solution + "', NGType=N'" + ng_type + "',"
                        + " SupplierID='" + supplier + "', NGKind=N'" + trouble_type + "', ResponsePerson=N'" + response + "',"
                        + " Remark=N'" + remark + "', AssNote=N'" + evaluation + "'"
                        + " WHERE ID=" + this.id;
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@exportdate", SqlDbType.DateTime).Value = exportdate.Date;
                    cmd_sql.Parameters.Add("@reportdate", SqlDbType.DateTime).Value = reportdate.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("F4 Export Trouble updated success.");
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show(ex.Message);
                    MessageBox.Show("Cannot update F4 Export Trouble. Please try again.");
                }
            }
            else
            {
                MessageBox.Show(error);
            }
        }
    }
}
